package com.starblink.store.search.ui

import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.core.widget.addTextChangedListener
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxItemDecoration
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.bean.LoadAction
import com.starblink.android.basic.brv.utils.divider
import com.starblink.android.basic.brv.utils.linear
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.color
import com.starblink.android.basic.ext.gone
import com.starblink.android.basic.ext.inflater
import com.starblink.android.basic.ext.string
import com.starblink.android.basic.ext.visible
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.util.FontUtil
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.widget.ConfirmDialog
import com.starblink.android.basic.widget.LoadingDialogManager
import com.starblink.basic.route.RoutePage
import com.starblink.basic.style.R
import com.starblink.basic.util.CommUtils
import com.starblink.basic.util.KeyboardUtils
import com.starblink.library.widget.holder.HistoryAdapter
import com.starblink.library.widget.sort.SortTypeEnum
import com.starblink.library.widget.sort.SortUtils
import com.starblink.store.databinding.ActivityStoreSearchBinding
import com.starblink.store.databinding.CellSimpleProductCardHorizontalBinding
import com.starblink.store.databinding.CellStoreSearchEmptyBinding
import com.starblink.store.databinding.CellStoreSearchRecommendTitleBinding

@Route(path = RoutePage.Store.PAGE_SEARCH)
class StoreSearchActivity : BaseTVMActivity<ActivityStoreSearchBinding, StoreSearchVM>() {

    @Autowired(name = RoutePage.Store.ID)
    @JvmField
    var storeId: String? = null

    private val historySearchWordsAdapter by lazyOnNone {
        HistoryAdapter(
            viewBinding.layoutSearchHistory.rvHistory,
            viewModel.historySearchWords
        ) {
            // 点击历史搜索词，开始搜索
            viewBinding.layoutTopBar.etSearchInput.setText(it)
            viewBinding.layoutTopBar.etSearchInput.setSelection(it.length)
            doSearchAction(it)
        }
    }

    // 店铺搜索结果列表Adapter
    private val adapter: MutableAdapter by lazyOnNone {
        MutableAdapter(viewModel.searchProducts).apply {
            addVhDelegate {
                SearchEmptyCell(
                    CellStoreSearchEmptyBinding.inflate(it.inflater, it, false)
                )
            }
            addVhDelegate {
                RecommendTitleCell(
                    CellStoreSearchRecommendTitleBinding.inflate(it.inflater, it, false)
                )
            }
            addVhDelegate {
                ProductCardHorizontalCell(
                    activity = this@StoreSearchActivity,
                    binding = CellSimpleProductCardHorizontalBinding.inflate(
                        it.inflater,
                        it,
                        false
                    ),
                    searchProducts = viewModel.searchProducts,
                    searchKeyword = viewModel.searchKeyword
                )
            }
        }
    }

    override fun initViewBinding(): ActivityStoreSearchBinding =
        ActivityStoreSearchBinding.inflate(layoutInflater)

    override fun initData() {
        super.initData()
        viewModel.storeId = storeId.toString()
    }

    override fun initView() {
        super.initView()

        initViewTopBar()
        initViewSearchHistory()
        initViewSort()
        initViewRvProducts()
        initViewBottomRightBtns()
    }

    private fun initViewTopBar() {
        viewBinding.layoutTopBar.etSearchInput.requestFocus()
        viewBinding.layoutTopBar.etSearchInput.setOnEditorActionListener { _, actionId, _ ->
            if (EditorInfo.IME_ACTION_SEARCH == actionId) {
                doSearchAction(viewBinding.layoutTopBar.etSearchInput.text.trim())
                true
            } else {
                false
            }
        }
        viewBinding.layoutTopBar.etSearchInput.addTextChangedListener {
            viewBinding.layoutTopBar.btnClear.visibleOrGone(it.toString().isNotEmpty())
        }
        viewBinding.layoutTopBar.btnClear.click {
            // 点击清除按钮，如果正在初始搜索页面，不用做任何操作；如果正在显示搜索结果，返回到初始搜索页面
            viewBinding.layoutTopBar.etSearchInput.setText("")
            if (viewBinding.page.visibility == View.VISIBLE) {
                // 隐藏搜索结果视图
                viewBinding.layoutSort.root.gone()
                viewBinding.page.gone()
                viewModel.searchProducts.clear()
                adapter.notifyDataSetChanged()

                viewModel.loadHistorySearchWords() // 重新加载搜索词
            }
        }
    }

    private fun initViewSearchHistory() {
        viewBinding.layoutSearchHistory.btnDelete.setOnClickListener {
            ConfirmDialog.Builder(this)
                .setCancelButton(R.string.cancel) { dialog, _ ->

                    dialog.dismiss()
                }
                .setSureButton(R.string.confirm) { dialog, _ ->
                    viewModel.clearHistorySearchWords()
                    dialog.dismiss()
                }
                .setTitle(R.string.clear_recent_view)
                .create().show()
        }

        viewBinding.layoutSearchHistory.rvHistory.layoutManager = FlexboxLayoutManager(this).apply {
            flexDirection = FlexDirection.ROW
            justifyContent = JustifyContent.FLEX_START
            maxLine = 10
            flexWrap = FlexWrap.WRAP
            // alignContent = AlignContent.FLEX_END // not support
        }
        viewBinding.layoutSearchHistory.rvHistory.addItemDecoration(FlexboxItemDecoration(this).apply {
            setDrawable(object : ColorDrawable(Color.TRANSPARENT) {
                override fun getIntrinsicWidth(): Int = 8.dp2px()
                override fun getIntrinsicHeight(): Int = 8.dp2px()
            })
        })
        viewBinding.layoutSearchHistory.rvHistory.adapter = historySearchWordsAdapter

        viewModel.historySearchWordsLD.observe(this) {
            viewBinding.layoutSearchHistory.root.visibleOrGone(it) {
                historySearchWordsAdapter.notifyItemRangeChanged(
                    0,
                    historySearchWordsAdapter.itemCount
                )
            }
        }
    }

    private fun initViewSort() {
        // 埋点：搜索结果页-sale按钮
        viewBinding.layoutSort.layoutFilterSale.trackData(
            page = SpmPageDef.StoreSearchResultPage,
            element = SpmElementDef.SEARCH_RESULT_SALE_BUTTON,
            params = mapOf("searchTerm" to viewModel.searchKeyword)
        )
        // 埋点：店铺搜索-排序
        fun trackSort() {
            SpmTrackHandler.addSingleTrackData(
                SkAntEntity(
                    spmCnt = GTrackerAssistUtils.fetchElementValue(
                        SpmPageDef.StoreSearchResultPage,
                        SpmElementDef.StoreListFeaturedClick
                    ),
                    params = mapOf("sorted" to viewModel.sortType.code.toString())
                )
            )
        }

        viewBinding.layoutSort.vSortPrice.setOnClickListener {
            // 显示排序弹窗
            SortUtils.showPriceSortPopup(
                context = mContext,
                alignView = viewBinding.layoutSort.vSortPrice,
                sortView = viewBinding.layoutSort.vSortPrice,
                selectedSortType = viewModel.sortType,
            ) {
                if (it.sortType == viewModel.sortType) {
                    return@showPriceSortPopup
                }

                setViewPriceSortSelected(it.text)

                viewModel.sortType = it.sortType
                trackSort()

                // 重新加载数据
                viewModel.searchProducts(refresh = true)
            }
        }

        viewBinding.layoutSort.layoutFilterSale.setOnClickListener {
            // 选中/取消选中Sale，更新数据
            viewModel.filterSale = !viewModel.filterSale
            setViewFilterSale(viewModel.filterSale)

            // 取消选中，并且当前排序项不是价格排序，重置排序方式
            if(!viewModel.filterSale && (viewModel.sortType == SortTypeEnum.DISCOUNT_H2L || viewModel.sortType == SortTypeEnum.DISCOUNT_L2H)) {
                viewModel.sortType = SortTypeEnum.DEFAULT
                setViewPriceSortSelected(string(R.string.recommended))
            }

            // 重新加载数据
            viewModel.searchProducts(refresh = true)
        }

        viewBinding.layoutSort.vSortDiscount.setOnClickListener {
            if (viewModel.sortType == SortTypeEnum.DISCOUNT_H2L) {
                // 从H2L变为L2H
                viewModel.sortType = SortTypeEnum.DISCOUNT_L2H
                viewBinding.layoutSort.vSortDiscount.icon =
                    CommUtils.getDrawable(com.starblink.library.widget.R.drawable.ic_svg_discount_l2h)
            } else {
                // 从L2H变为H2L,或者从normal变为H2L
                viewModel.sortType = SortTypeEnum.DISCOUNT_H2L
                setViewDiscountSortSelected()
            }
            // 取消Price排序
            viewBinding.layoutSort.vSortPrice.setTextColor(CommUtils.getColor(com.starblink.basic.style.R.color.gu_text_secondary))
            viewBinding.layoutSort.vSortPrice.typeface =
                FontUtil.getTypeface(FontUtil.MONTSERRAT_MEDIUM)
            viewBinding.layoutSort.vSortPrice.iconTint =
                ColorStateList.valueOf(color(com.starblink.basic.style.R.color.gu_text_secondary))

            trackSort()

            // 重新加载数据
            viewModel.searchProducts(refresh = true)
        }
    }

    /**
     * 显示初始状态的排序视图
     */
    private fun showInitStateSortView(showSale: Boolean) {
        viewBinding.layoutSort.root.visible()

        // 默认排序
        viewModel.sortType = SortTypeEnum.DEFAULT
        setViewPriceSortSelected(string(R.string.recommended))

        // 默认不过滤Sale
        viewModel.filterSale = false

        // 默认Sale不勾选
        setViewFilterSale(false)
        // 根据接口字段判断是否显示
        viewBinding.layoutSort.layoutFilterSale.visibleOrGone(showSale)
    }

    /**
     * 设置价格排序选中样式（自定义显示文本）
     */
    private fun setViewPriceSortSelected(text: String) {
        // 取消Discount排序
        setViewDiscountSortUnselected()

        // Price排序设置为选中
        viewBinding.layoutSort.vSortPrice.text = text
        viewBinding.layoutSort.vSortPrice.setTextColor(CommUtils.getColor(com.starblink.basic.style.R.color.gu_text_primary))
        viewBinding.layoutSort.vSortPrice.typeface =
            FontUtil.getTypeface(FontUtil.MONTSERRAT_SEMIBOLD)
        viewBinding.layoutSort.vSortPrice.iconTint =
            ColorStateList.valueOf(color(com.starblink.basic.style.R.color.gu_text_primary))
    }

    /**
     * 设置FilterSale按钮选中/未选中
     */
    private fun setViewFilterSale(checked: Boolean) {
        viewBinding.layoutSort.ivFilterSaleCheckbox.setImageResource(
            if (checked) com.starblink.library.widget.R.drawable.ic_svg_checkbox_black_checked
            else com.starblink.library.widget.R.drawable.ic_svg_checkbox_black_normal
        )
        viewBinding.layoutSort.vFilterSaleIcon.visibleOrGone(checked)
        viewBinding.layoutSort.vFilterSaleLottieIcon.visibleOrGone(!checked)

        //显示Discount按钮
        viewBinding.layoutSort.vSortDiscount.visibleOrGone(checked) {
            setViewDiscountSortUnselected()
        }
    }

    /**
     * 设置Discount排序未选中
     */
    private fun setViewDiscountSortUnselected() {
        viewBinding.layoutSort.vSortDiscount.backgroundTintList =
            ColorStateList.valueOf(color(R.color.gu_bg_light1))
        viewBinding.layoutSort.vSortDiscount.setTextColor(CommUtils.getColor(R.color.gu_text_secondary))
        viewBinding.layoutSort.vSortDiscount.strokeWidth = 0
        viewBinding.layoutSort.vSortDiscount.icon =
            CommUtils.getDrawable(com.starblink.library.widget.R.drawable.ic_svg_discount_normal)
    }

    private fun setViewDiscountSortSelected() {
        viewBinding.layoutSort.vSortDiscount.backgroundTintList =
            ColorStateList.valueOf(color(R.color.gu_bg_brand1))
        viewBinding.layoutSort.vSortDiscount.setTextColor(color(R.color.gu_text_data_brand))
        viewBinding.layoutSort.vSortDiscount.strokeWidth = 1.dp2px()
        viewBinding.layoutSort.vSortDiscount.icon =
            CommUtils.getDrawable(com.starblink.library.widget.R.drawable.ic_svg_discount_h2l)
    }

    private fun initViewRvProducts() {
        viewBinding.rv.linear().divider {
            setDivider(16, true)
        }

        viewBinding.page.onRefresh {
            // 错误重试
            viewModel.searchProducts(refresh = true, isShowInitStateSortView = true)
        }

        viewBinding.page.onLoadMore {
            if (viewModel.searchResultEmpty) {
                viewModel.loadRecommendProducts(refresh = false)
            } else {
                viewModel.searchProducts(refresh = false)
            }
        }

        viewModel.searchResultLD.observe(this) {
            if (it.isRefresh) {
                if (it.isShowInitStateSortView) {
                    // 仅当搜索新文本，并成功返回搜索结果时，显示初始状态排序视图
                    showInitStateSortView(it.isShowSale)
                } else if (viewModel.searchResultEmpty) {
                    // 搜索结果为空，显示空视图时，隐藏排序视图
                    viewBinding.layoutSort.root.gone()
                }
            }

            // 显示列表数据
            if (viewBinding.rv.adapter == null) {
                // 当显示搜索结果首页数据时 或 搜索结果为空显示空视图+推荐商品列表首页时，执行此处逻辑
                viewBinding.rv.adapter = adapter
            } else {
                adapter.notifyDataSetChanged()
            }
            viewBinding.page.showContent()
            viewBinding.vWishList.visible()
            LoadingDialogManager.get().dismissLoading()
        }

        viewModel.mLoadActionLiveData.observe(this) {
            LoadingDialogManager.get().dismissLoading()
            when (it.action) {
                LoadAction.STATE_ERROR -> {
                    viewBinding.page.showError(it.errorCode)
                }

                LoadAction.STATE_NO_DATA -> {
                    viewBinding.page.finishLoadMoreWithNoMoreData()
                }
            }
        }
    }

    private fun initViewBottomRightBtns() {
        // 点击心愿单按钮，跳转到首页心愿单
        viewBinding.vWishList.setOnClickListener {
            FlowBus.intFlowBusNotify(FlowConst.WISH_INDEX_CHANGE, 3)
        }
    }

    override fun initObservable() {
        super.initObservable()
    }

    override fun initLoad() {
        super.initLoad()
        // 打开页面，默认加载显示历史搜索词
        viewModel.loadHistorySearchWords()
        // 自动显示软键盘
        viewBinding.root.postDelayed({
            KeyboardUtils.showSoftkeyboard(this)
        }, 200)
    }

    /**
     * 执行搜索动作
     */
    private fun doSearchAction(searchContent: CharSequence?) {
        if (searchContent.isNullOrEmpty()) return
        val keyword = searchContent.toString()
        viewModel.searchKeyword = keyword
        viewModel.sortType = SortTypeEnum.DEFAULT
        viewModel.saveToHistorySearchWords(keyword)

        // 隐藏搜索历史，显示LoadingView
        viewBinding.layoutSearchHistory.root.gone()
        viewBinding.page.visible()

        viewModel.searchProducts(refresh = true, isShowInitStateSortView = true)
    }

    override fun onResume() {
        super.onResume()
        pageExposure(SpmPageDef.StoreSearchResultPage)
    }

    override fun onPause() {
        super.onPause()
        pageDisappear(SpmPageDef.StoreSearchResultPage)
    }
}